package com.earthchen.gps.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据库连接池配置
 *
 * @author: EarthChen
 * @date: 2018/04/27
 */
public class DBPoolConnection {

    private static DBPoolConnection dbPoolConnection = null;
    private static DruidDataSource druidDataSource = null;

    static {
        Properties properties = loadPropertiesFile("/db_server.properties");
        try {
            //DruidDataSrouce工厂模式
            druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            System.out.println("获取配置失败");
        }
    }

    /**
     * 数据库连接池单例
     *
     * @return
     */
    public static synchronized DBPoolConnection getInstance() {
        if (null == dbPoolConnection) {
            dbPoolConnection = new DBPoolConnection();
        }
        return dbPoolConnection;
    }

    /**
     * 返回druid数据库连接
     *
     * @return
     * @throws SQLException
     */
    public DruidPooledConnection getConnection() throws SQLException {
        return druidDataSource.getConnection();
    }

    /**
     * 加载数据库配置文件
     *
     * @param fullFile
     * @return
     */
    private static Properties loadPropertiesFile(String fullFile) {
        Properties prop = new Properties();
        try {
            prop.load(DBPoolConnection.class.getResourceAsStream(fullFile));
        } catch (IOException e) {
            System.out.println("数据库连接池配置文件加载错误");
        }
        return prop;
    }
}
